<template>
  <div class="front">
    <el-input v-model="searchForm.name" @keyup.enter="handleSearch" placeholder="请输入查询关键字" style="width: 400px;">
      <template v-slot:prepend>
        <el-select v-model="searchType" placeholder="搜索方式" style="width: 100px;">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </template>
    </el-input>
    <el-button @click="handleSearch" class="search" type="primary">查询</el-button>
  </div>

  <div class="tail">
    <div class="tail-action">
      <el-button type="primary" @click="handleOpenAdd">新增角色</el-button>
      <!-- <el-button type="primary" @click="handleChangeStatus">启用/停用</el-button> -->
    </div>
    <el-table :data="tableData()" border style="width: 100%">
      <el-table-column type="selection" width="40" />
      <el-table-column prop="roleCode" label="角色编码" min-width="60" />
      <el-table-column prop="roleName" label="角色名称" min-width="60" />
      <!-- <el-table-column prop="status" label="角色状态" width="100" :filter-multiple="false" :filters="[
        { text: '启用', value: 0 },
        { text: '停用', value: 1 },
      ]" :filter-method="filterTag" filter-placement="bottom-end">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'success' : 'danger'" disable-transitions>{{ scope.row.status == 0 ? '启用'
            : '停用'
          }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="remark" label="备注" min-width="60" />
      <el-table-column prop="createTime" label="创建时间" min-width="60" />
      <el-table-column fixed="right" label="操作" min-width="60">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOpenEdit(scope.row)">编辑</el-button>
          <el-button link type="primary" size="small" @click="handleDeleteRole(scope.row.roleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
        layout="prev, pager, next ,total,sizes" :total="data.total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>

  <div class="dialog-list">
    <!-- 新增角色 -->
    <el-dialog v-model="dialogVisible1" title="新建角色" class="dialog-add" width="40%" close-on-click-modal
      :before-close="handleClose" :show-close="false">
      <div>
        <el-form :model="roleForm" label-width="120px" :rules="roleRules" ref="roleRef">
          <el-form-item label="角色名称" prop="roleName" :required="true">
            <el-input v-model="roleForm.roleName" />
          </el-form-item>
          <el-form-item label="角色编码" :required="true">
            <el-input v-model="roleForm.roleCode" disabled />
          </el-form-item>
          <el-form-item label="角色权限" style="overflow: auto; max-height: 400px;" prop="menuLabelList">
            <el-tree ref="treeAddRef" :data="menuList" show-checkbox node-key="id" :default-checked-keys="addCheckedKeys"
              @check-change="handleCheckChange">
            </el-tree>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="roleForm.remark" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleAddRole">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog v-model="dialogVisible2" title="编辑角色" width="40%" :before-close="handleClose" close-on-click-modal
      :show-close="false">
      <div>
        <el-form :model="roleForm" label-width="120px" :rules="roleRules" ref="roleRef">
          <el-form-item label="角色名称" prop="roleName" :required="true">
            <el-input v-model="roleForm.roleName" />
          </el-form-item>
          <el-form-item label="角色权限" style="overflow: auto; max-height: 400px;" prop="role">
            <el-tree ref="treeEditRef" :data="editRoleMemus" show-checkbox node-key="id"
              @check-change="handleCheckChange"></el-tree>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="roleForm.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose('edit')">取消</el-button>
          <el-button type="primary" @click="handleUpdateRole">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script >
import { ref, defineComponent, reactive, toRefs, nextTick } from "vue";
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowDownBold } from '@element-plus/icons-vue'
import { onMounted } from "vue";
import { addRole, getRoleList, deleteRole, getRoleInfo, getRoleCode, getMenuList, updateRole, search } from "@/api/auth/auth"
export default defineComponent({
  name: "UserRole",
  components: {
    ArrowDownBold
  },

  setup() {
    let roleData = reactive({
      data: [],
    });
    const roleForm = reactive({
      roleName: '',
      roleKey: '',
      roleSort: '1',
      roleCode: '',
      menuIds: [],
      remark: '',
      status: 0,
    });
    const MenuchildrenVisible = ref(false)
    const searchForm = reactive({
      name: '',
    });
    const roleMenuRef = ref()
    const roleRef = ref(null)
    const menuList = ref([])
    const menuLabelList = ref([])
    const selectedMenu = ref([])
    const dialogVisible1 = ref(false)
    const dialogVisible2 = ref(false)
    const roleRules = reactive({
      roleName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 2, max: 8, message: '名称长度 在 2 到 8长度之间', trigger: 'blur' }],
      remark: [{ required: false, message: '请输入内容', trigger: 'blur' }],
    });
    const defaultProps = reactive({
      children: 'children',
      label: 'label'
    }
    )
    const treeAddRef = ref(null)
    const treeEditRef = ref(null)

    const editRoleMemus = ref([]) // 编辑窗口保存菜单数据数组
    const editCheckedKeys = ref([]) // 选中的数据数组
    const addCheckedKeys = ref([])

    const searchType = ref(null)
    const options = reactive([
      { value: '0', label: '角色名称' }, { value: '1', label: '角色编码' },
    ])
    //表格用到的参数
    let state = reactive({
      data: {
        page: 1,
        limit: 10,
        total: roleData.data.length,
      }
    });

    const filterTag = (value, row) => {
      return row.status == value
    }

    onMounted(() => {//获取数据
      getMenuList().then((res) => {
        menuList.value = res.menus
      })
      handleGetRoleList(state.data.page, state.data.limit)
    })

    const handleGetRoleList = (page, limit) => {
      getRoleList(page, limit).then((res) => {
        roleData.data = res.rows
        state.data.total = res.total
      })
    }
    const tableData = () => {
      return roleData.data
    };
    //改变页码
    const handleCurrentChange = (e) => {
      state.page = e;
      handleGetRoleList(e, state.data.limit)
    };
    //改变页数限制
    const handleSizeChange = (e) => {
      state.limit = e;
      handleGetRoleList(state.data.page, e)
    };
    // 添加角色 —— 提交数据
    const handleAddRole = () => {
      const arr = treeAddRef.value.getCheckedKeys()
      arr.forEach((item) => {
        roleForm.menuIds.push(item)
      })
      roleForm.roleSort = '1'
      roleRef.value.validate().then(() => {//验证通过
        roleForm.roleKey = roleForm.roleCode
        ElMessageBox.confirm('确认提交?')
          .then(() => {
            roleForm.roleKey = roleForm.roleName
            addRole(roleForm).then((res) => {
              res.code == 500 ? ElMessage.error(res.msg) : ElMessage.success('添加成功')
              roleRef.value.resetFields()
              dialogVisible1.value = false
              handleGetRoleList(state.data.page, state.data.limit)
            })
          })
          .catch(() => {// catch error
          })
      }).catch(() => {
      })
    }
    //删除角色
    const handleDeleteRole = (roleId) => {
      ElMessageBox.confirm(
        '是否要删除该角色?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          deleteRole(roleId).then((res) => {
            if (res.code == 500) {
              ElMessage.error(res.msg)
            } else {
              ElMessage.success("删除角色成功")
            }
            handleGetRoleList(state.data.page, state.data.limit)
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }

    const handleUpdateRole = () => {//修改角色
      roleRef.value.validate().then(() => {//验证通过
        ElMessageBox.confirm('确认提交?')
          .then(() => {
            // roleForm.menuIds = roleForm.menuIds.map(item => item.id)
            updateRole(roleForm).then((res) => {
              if (res.code == 500) {
                ElMessage.error(res.msg)
              } else {
                ElMessage.success("修改角色成功")
              }
              dialogVisible2.value = false
              handleGetRoleList(state.data.page, state.data.limit)
            })
          })
          .catch(() => {// catch error
          })
      }).catch(() => {
      })
    }
    const handleOpenAdd = () => {//打开新增角色
      dialogVisible1.value = true
      nextTick(() => {
        roleRef.value.resetFields()
        roleForm.roleId = ''
        roleForm.roleSort = ''
        roleForm.roleName = ''
        roleForm.remark = ''
      })
      getRoleCode().then((res) => {
        roleForm.roleCode = res
      })
    }
    const handleOpenEdit = (data) => { //打开编辑角色
      getRoleInfo(data.roleId).then((res) => {
        editRoleMemus.value = [...res.menus]
        editCheckedKeys.value = [...res.checkedKeys]
        console.log('checkedKeys', res.checkedKeys);
        treeEditRef.value.setCheckedKeys([...res.checkedKeys])
      })
      roleForm.menuIds = []
      roleForm.roleName = data.roleName
      roleForm.roleKey = data.roleName
      roleForm.remark = data.remark
      roleForm.roleId = data.roleId
      dialogVisible2.value = true
    }
    const updateData = () => {
      menuList.value.splice()
    }
    const isChecked = (id) => {

      if (selectedMenu.value.includes(id)) {
        roleForm.menuIds.push(menuList.value.map(item => item.id))
      }
      return selectedMenu.value.includes(id)
    }
    const handleClose = (e) => { // 关闭新增 / 修改窗口
      // roleForm.menuIds = []
      // roleForm.roleName = ''
      // roleForm.roleKey = ''
      dialogVisible2.value = false
      dialogVisible1.value = false
      // nextTick( () => {
      //   roleRef.value.resetFields()
      // })
      treeAddRef.value && treeAddRef.value.setCheckedKeys([])
      treeEditRef.value && treeEditRef.value.setCheckedKeys([])
      // console.log('清除啦');
      // console.log(roleForm);
    }
    const RoleChange = (val) => {//控制权限复选框
      menuList.value.forEach(item => {
        if (val.every(childrenVal => item.children.map(element => element.label).includes(childrenVal))) {
          item.isIndeterminate = true
          if (val.length == item.children.length) {
            item.isIndeterminate = false
            item.checked = true
          }
        } else {
          item.isIndeterminate = false
        }
        if (val.length == 0) {
          item.isIndeterminate = false
        }
      })
    }

    const RoleMenuChange = (val) => {
      roleForm.menuIds = []
      menuList.value.forEach(element => {//重置状态
        element.checked = false
      });
      menuList.value.forEach(element => {//获取勾选状态
        if (val.some(value => value == element.label)) {
          element.checked = true;
        }
      });
      menuList.value.forEach(element => {//根据勾选添加子级勾选
        if (element.checked) {
          element.isIndeterminate = false
          element.checkedChildren = element.children.map(childItem => childItem.label)
          element.children.forEach(childItem => {
            roleForm.menuIds.push(childItem.id);
          })
        } else {
          element.isIndeterminate = false
          element.checkedChildren = []

        }
      })
    }

    const handleChangeStatus = () => {
      // changeStatus(statusForm.data).then((res) => {
      //   res.code==200?ElMessage.success('修改成功'):ElMessage.error(res.msg)
      //   handleGetUserList(state.data.page, state.data.limit)
      // })
    };

    const handleCheckChange = (data, checked, indeterminate) => {
      // console.log( data, checked, indeterminate );
    }

    // 处理查询角色名称
    const handleSearch = () => {
      const pageSize = 10
      const pageNum = 1
      const paramsObj = { pageSize, pageNum }
      if (searchType.value == 0) {
        paramsObj.roleName = searchForm.name
      } else {
        paramsObj.roleCode = searchForm.name
      }
      console.log('shuju', paramsObj);
      getRoleList(paramsObj).then((res) => {
        roleData.data = res.rows
        state.data.total = res.total
      })
    }
    return {
      roleData, roleMenuRef, menuList, menuLabelList, addCheckedKeys, editRoleMemus, editCheckedKeys,
      dialogVisible1, selectedMenu, dialogVisible2,
      searchForm, searchType, options,
      roleForm, MenuchildrenVisible,
      roleRules, roleRef, treeAddRef, treeEditRef,
      tableData, filterTag, isChecked,
      handleCurrentChange, handleOpenAdd,
      handleSizeChange, handleUpdateRole,
      handleClose, updateData, handleChangeStatus,
      handleDeleteRole, handleAddRole, handleGetRoleList,
      handleOpenEdit, handleCheckChange,
      RoleChange, RoleMenuChange,
      ...toRefs(state), handleSearch
    };
  },
});
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #fff;
  padding: 10px;
  display: flex;

  .input {
    // float: left;
  }

  .search {
    margin-left: 50px;
  }
}

.center {
  margin: 10px;
}


.tail {
  background-color: #fff;
  margin-top: 40px;
  padding: 10px;

  .tail-action {
    margin-bottom: 10px;
    display: flex;
  }
}

.el-checkbox__label {
  display: flex;
  margin-left: 10px;
}

.form-add-checkbox {
  width: 100%;
}

.dialog-list {
  .dialog-add {
    width: 40%;

    .dialog-menu {}
  }

}
</style>
